<!--  -->
<template>
  <div class="index" ref="mainBox">
    <!-- 导航栏 -->
    <div :class="{ fixed: true, active: isColor }">
      <div class="container">
        <div class="navbar-logo" @click="backTop">
          <img src="../../assets/logo.png" alt="" />
        </div>
        <div class="navbar-left">
          <fc-typing-input
            white
            placeholder="输 入 车 名 查 找 :)"
            @change="changeInput($event)"
            @input="changeInput($event)"
            @keyup.enter="search"
          ></fc-typing-input>
          <fc-3d-btn @click="search">搜索</fc-3d-btn>
        </div>
        <!-- 未登录 -->
        <div class="navbar-right" v-if="IsLogin != undefined">
          <!-- 头像 -->
          <div
            @click="toPersonView"
            style="display: flex; cursor: pointer; margin-right: 20px"
          >
            <el-avatar
              :size="size"
              :src="avatar == '默认头像' ? avatar_url : this.api_url + avatar"
            ></el-avatar>
            <div class="username" style="margin: auto 0">
              <p>{{ nickname }}</p>
            </div>
          </div>
          <fc-parenthesis-btn
            style="
              :host {
                --color: #fff;
              }
            "
            @click="switchIsLogin()"
            >退出登录</fc-parenthesis-btn
          >
        </div>
        <!-- 登录成功 -->
        <div class="navbar-right" v-else>
          <fc-parenthesis-btn @click="loginVisible = true"
            >登 录
          </fc-parenthesis-btn>
        </div>
      </div>
    </div>

    <!-- 登录表单 -->
    <el-dialog title="登 录" :visible.sync="loginVisible" width="500px">
      <!-- 表单 -->
      <el-tabs v-model="activeName">
        <!-- 验证码 Verification Code -->
        <el-tab-pane label="验证码登录" name="first">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <!-- 手机号码 -->
            <el-form-item
              label="手机号码"
              prop="uphone"
              style="margin-bottom: 30px"
            >
              <el-input
                type="text"
                v-model="ruleForm.uphone"
                autocomplete="off"
                style="font-size: 18px"
              ></el-input>
            </el-form-item>

            <!-- 验证码 -->
            <el-form-item label="验 证 码" prop="VerCode">
              <el-input
                type="text"
                v-model="ruleForm.VerCode"
                autocomplete="off"
                style="font-size: 18px"
              ></el-input>
            </el-form-item>

            <el-form-item style="margin-top: 25px">
              <el-button
                type="primary"
                @click="VerCode_login()"
                style="margin-right: 20px; font-size: 18px; border-radius: 10px"
                >登 录 / 注 册</el-button
              >
              <el-button
                @click="getVerCode(60)"
                style="font-size: 18px; border-radius: 10px"
                v-text="VerCode_text"
                :disabled="disable"
              >
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 密码 -->
        <el-tab-pane label="密码登录" name="second">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <!-- 手机号码 -->
            <el-form-item
              label="手机号码"
              prop="uphone"
              style="margin-bottom: 30px"
            >
              <el-input
                type="text"
                v-model="ruleForm.uphone"
                autocomplete="off"
                style="font-size: 18px"
              ></el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密 码" prop="upwd">
              <el-input
                type="password"
                v-model="ruleForm.upwd"
                autocomplete="off"
                style="font-size: 18px"
              >
              </el-input>
            </el-form-item>

            <el-form-item style="margin-top: 25px">
              <el-button
                type="primary"
                @click="Pwd_login()"
                style="
                  width: 170px;
                  font-size: 18px;
                  margin-right: 88px;
                  border-radius: 10px;
                "
                >登 录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { FcUnderlineBtn } from "fancy-components";
import { Fc3DBtn } from "fancy-components";
import { mapMutations, mapState } from "vuex";

new FcUnderlineBtn();
new Fc3DBtn();

export default {
  name: "HomeContainer",
  computed: {
    ...mapState([
      "avatar_url",
      "IsLogin",
      "nickname",
      "avatar",
      "uid",
      "api_url",
    ]),
  },

  data() {
    // 用户名判断
    let uphone = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入手机号码"));
      } else {
        if (!/^1[3-9]\d{9}$/.test(this.ruleForm.uphone)) {
          callback(new Error("手机号码错误"));
        } else {
          this.$refs.ruleForm.validateField("VerCode");
          this.$refs.ruleForm.validateField("upwd");
        }
        callback();
      }
    };
    // 验证码判断
    let VerCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    // 密码判断
    let upwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        uphone: "",
        upwd: "",
        VerCode: "",
      },

      rules: {
        uphone: [{ validator: uphone, trigger: "blur" }],
        VerCode: [{ validator: VerCode, trigger: "blur" }],
        upwd: [{ validator: upwd, trigger: "blur" }],
      },
      activeName: "second",
      isColor: false,

      // 登录框
      loginVisible: false,

      VerCode_text: "获 取 验 证 码",

      // 定时器
      timer: null,

      // 存储验证码
      authcode: null,

      // 按钮不可用
      disable: false,

      size: null,
    };
  },

  watch: {},

  //方法集合
  methods: {
    ...mapMutations(["updateIsLogin", "updateUid", "LoginOut"]),

    scroll_top() {
      this.box = this.$refs.mainBox;
      this.box.addEventListener("scroll", () => {
        console.log(this.$refs.mainBox.scrollTop);
        if (this.$refs.mainBox.scrollTop > 80) {
          this.isColor = true;
        } else {
          this.isColor = false;
        }
      });
    },

    // 搜索
    changeInput(e) {
      this.searchKey = e.target.value;
    },

    search() {
      if (this.searchKey == undefined) {
        this.searchKey = "";
      }
      this.$router.push(`/search/${this.searchKey}`);
    },

    // 验证码登录
    VerCode_login() {
      // 用户
      let user = {
        phone: this.ruleForm.uphone,
        authcode: this.ruleForm.VerCode,
      };
      if (this.ruleForm.uphone != "") {
        if (this.ruleForm.VerCode != "") {
          this.axios
            .post("/user/login", `${JSON.stringify(user)}`, {
              headers: {
                // 设置请求头
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.data.status == 20000) {
                this.$message({
                  message: "登陆成功！",
                  type: "success",
                  duration: 1000,
                });
                let timer = setTimeout(() => {
                  this.setLocalStorage(res.data.data);
                  this.loginVisible = false;
                  clearTimeout(timer);
                  this.$router.go(0);
                }, 1000);
              } else {
                this.$message({
                  message: res.data.msg,
                  type: "error",
                  duration: 1500,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message({
            message: "验证码不能为空",
            type: "error",
            duration: 1500,
          });
        }
      } else {
        this.$message({
          message: "手机号不能为空",
          type: "error",
          duration: 1500,
        });
      }
    },

    // 密码登录
    Pwd_login() {
      // 用户
      let user = {
        phone: this.ruleForm.uphone,
        password: this.ruleForm.upwd,
      };
      if (this.ruleForm.uphone != "") {
        if (this.ruleForm.upwd != "") {
          this.axios
            .post("/user/password-login", `${JSON.stringify(user)}`, {
              headers: {
                // 设置请求头
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.data.status == 20000) {
                this.$message({
                  message: "登陆成功！",
                  type: "success",
                  duration: 1500,
                });
                let timer = setTimeout(() => {
                  this.setLocalStorage(res.data.data);
                  this.loginVisible = false;
                  clearTimeout(timer);
                  this.$router.go(0);
                }, 1500);
              } else {
                this.$message({
                  message: "手机号未注册或密码错误！",
                  type: "error",
                  duration: 1500,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message({
            message: "密码不能为空",
            type: "error",
            duration: 1500,
          });
        }
      } else {
        this.$message({
          message: "手机号不能为空",
          type: "error",
          duration: 1500,
        });
      }
    },

    // 获取验证码
    getVerCode(num) {
      this.axios
        .post(
          "/user/get-AuthCode",
          `${JSON.stringify({ phone: this.ruleForm.uphone })}`,
          {
            headers: {
              // 设置请求头
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          console.log(res.data.data);
          this.authcode = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
      this.disable = true;
      this.timer = setInterval(() => {
        num--;
        this.VerCode_text = num + "秒后再次发送";
        if (num == 0) {
          this.disable = false;
          this.VerCode_text = `获取验证码`;
          clearTimeout(this.timer);
        }
      }, 1000);
    },

    // 存储所需数据
    setLocalStorage(res) {
      this.updateIsLogin({
        IsLogin: true,
        token: res.token,
        phone: res.phone,
        nickname: res.nickname,
        avatar: res.avatar,
        uid: res.id,
      });
    },

    // 退出登录
    switchIsLogin() {
      this.LoginOut();
      if (this.$route.path != "/") {
        this.$router.push("/");
        this.$router.go(0);
      }
    },

    // 个人信息页面
    toPersonView() {
      this.$router.push(`/personview/${this.uid}`);
    },

    // 返回顶部
    backTop() {
      document.documentElement.scrollTop = document.body.scrollTop = 0;
    },
  },
};
</script>

<style lang='scss'>
.index {
  user-select: none;
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  overflow: auto;

  .fixed {
    position: fixed;
    top: 0;
    left: 0;
    background-color: #34373c;
    text-align: center;
    font-size: 30px;
    width: 100vw;
    transition: all 0.3s ease-in-out;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    z-index: 2006;
  }

  /* 导航栏主容器 */
  .fixed .container {
    height: 75px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.3s ease-in-out;
    overflow: hidden;
  }

  .fixed.active .container {
    padding: 6px;
    background-color: #333;
  }

  .active {
    background: #000;
  }

  .navbar-logo {
    margin-left: 110px;
    width: 220px;
    cursor: pointer;

    img {
      width: 100%;
      display: block;
    }
  }

  /* 导航栏左右分栏 */
  .navbar-left {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 220px;
  }

  .navbar-right {
    width: 45%;
    height: 100%;
    top: 0;
    margin: 10px;
    margin-right: 30px;
    display: flex;
    justify-content: flex-end;
    flex-direction: row;
    align-items: center;
  }

  /* 导航栏按钮 */
  /* 按钮 */
  fc-parenthesis-btn {
    --color: #fff;
    margin: 10px;
  }

  fc-underline-btn {
    --color: #fff;
  }

  fc-typing-input {
    width: 430px;
  }

  fc-3d-btn {
    margin: 10px;
    --shadow-color: rgb(89, 100, 122);
    --cover-color: rgb(231, 224, 173);
    --inset-shadow-color: rgb(245, 243, 239);
    --color: #333;
    color: #fff;
  }

  fc-typing-input {
    --color: #fff;
    --circle-color: #fff;
    --circle-color-hover: #fff;
    --placeholder-animate-title-color: #333;
  }

  //登录栏用户名样式
  .username {
    color: #fff;
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
      "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    font-size: 6px;
    width: 95px;

    text-align: left;
    padding-left: 5px;
  }
  .el-dialog {
    border-radius: 14px;

    .el-dialog__header {
      padding: 24px 0 0 0;

      .el-dialog__title {
        font-size: 20px;
      }
    }

    .el-dialog__body {
      padding-top: 0;
    }
  }

  .el-message {
    top: 80px !important;
  }
}
</style>